<template>
  <div class="phone-login">
    <el-form ref="loginFormRef" :model="authStore.phoneLoginForm"
             :rules="rules" class="login-form"
             autocomplete="on" label-position="left"
             @submit.native.prevent>
      <el-form-item prop="phoneNumber" class="form-item">
        <el-input
            v-model="authStore.phoneLoginForm.phoneNumber"
            placeholder="请输入手机号" clearable
        >
          <template #prefix>
            <i class="fa-solid fa-mobile-screen"></i>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="code" class="code-item">
        <el-input
            v-model="authStore.phoneLoginForm.code"
            placeholder="请输入验证码" type="password"
            show-password clearable
        >
          <template #prefix>
            <i class="fa-solid fa-shield-halved"></i>
          </template>
        </el-input>

        <el-button type="primary"
                   :disabled="authStore.isGettingCode"
                   @click="authStore.getAuthCode('phone')">
          {{ authStore.isGettingCode ? authStore.getCodeCountdown + 's' : '获取验证码' }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-button type="primary" style="width: 100%;"
               :loading="authStore.loginLoading"
               @click.prevent="handleLogin()">登录
    </el-button>

    <el-button style="width: 100%;margin-left: 0;"
               @click="authStore.changeLoginType('common')">取消
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { useAuthStore } from '@/store/auth'
import { useRouter } from 'vue-router'
import { ElMessage, FormRules } from 'element-plus'
import { reactive, ref } from 'vue'
import { loginRules } from '@/utils/element/elRules'

const rules = reactive<FormRules>(loginRules)
const authStore = useAuthStore()
const router = useRouter()

const loginFormRef = ref()

const handleLogin = async () => {
  loginFormRef.value.validate(async (valid: any) => {
    if (valid) {
      authStore.loginLoading = true

      try {
        await authStore.handleLogin('phone')
        await router.push('/home')
      } finally {
        authStore.loginLoading = false
      }
    } else {
      ElMessage.error('请输入正确的信息')
      return false
    }
  })
}
</script>
